package com.qingdai.service.impl;

import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.qingdai.emuns.*;
import com.qingdai.mapper.CommodityMapper;
import com.qingdai.mapper.OrderEsMapper;
import com.qingdai.mapper.OrderMapper;
import com.qingdai.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author LiuZiMing
 * @since 2024-01-26
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderEsMapper orderEsMapper;
    @Resource
    private CommodityMapper commodityMapper;

    @Override
    public Iterable<Order> saveOrders(List<Order> allOrders) {
        return orderEsMapper.saveAll(allOrders);
    }

    @Override
    public List<OrderDTO> getOrderDTOById(Integer id) {
        MPJLambdaWrapper<Order> wrapper = new MPJLambdaWrapper<>();
        wrapper.eq("t.id", id)
                .selectAll(Order.class)
                .selectAs(Shop::getName, OrderDTO::getShopName)
                .leftJoin(Shop.class, Shop::getId, Order::getShopId)
                .selectAs(User::getName, OrderDTO::getBuyerName)
                .leftJoin(User.class, User::getId, Order::getBuyerId)
//                .selectAs(Commodity::getTitle, OrderDTO::getCommodityNameList)
//                .leftJoin(Commodity.class, Commodity::getId, Order::getCommodityIdList)
        ;
        List<OrderDTO> orderDTOList = orderMapper.selectJoinList(OrderDTO.class, wrapper);
        //把commodity_id_list拆分查询并放入commodityNameList
        for (int i = 0; i < orderDTOList.size(); i++) {
            String commodityIdListString = orderDTOList.get(i).getCommodityIdList();
            String[] commodityIdArray = commodityIdListString.split(",");
            List<String> commodityNameList = new ArrayList<>();
            for (int j = 0; j < commodityIdArray.length; j++) {
                Commodity commodity = commodityMapper.selectById(commodityIdArray[j]);
                commodityNameList.add(commodity.getTitle());
            }
            String commodityNameListName = String.join(",", commodityNameList);
            orderDTOList.get(i).setCommodityNameList(commodityNameListName);
        }

        return orderDTOList;
    }


}
